const { QueryTypes, Op } = require("sequelize");
const seq = require("../db/seq");
const { TagAddError } = require("../constant/err.type");
const TagModel = require("../model/tag.model");
const moment = require("moment");
class TagService {
  async queryList(params = null) {
    let offset = (params.page - 1) * params.size;
    console.log(params, "obj");
    if (params && params.tagName) {
      const { tagName } = params;
      const total = await TagModel.count({
        where: {
          tagName:{
            [Op.like]: `%${tagName}%`,
          }
        },
      });
      console.log(total,"@@@@")
      const res = await seq.query(
        "select * from `bl-tag` where tagName like :tagName limit :limit offset :offset",
        {
          replacements: { tagName: `%${tagName}%`, offset, limit: params.size },
          type: QueryTypes.SELECT,
        }
      );
      console.log(res, "---res");
      return {
        data: res,
        total,
        currentPage: params.page,
        pageSize: params.size,
      };
    } else {
      const total = await TagModel.count();
      const res = await seq.query(
        "select * from `bl-tag` limit :limit offset :offset",
        {
          replacements: { offset, limit: params.size },
          type: QueryTypes.SELECT,
        }
      );
      return {
        data: res,
        total,
        currentPage: params.page,
        pageSize: params.size,
      };
    }
  }

  async modifyService({ id, tagName }) {
    const res = await seq.query(
      "update `bl-tag` set tagName = ? where id = ?",
      {
        replacements: [tagName, id],
        type: QueryTypes.UPDATE,
      }
    );
    return res;
  }

  async addService({ tagName }) {
    const time = moment().valueOf();
    const res = await seq.query(
      "insert into `bl-tag` (tagName,createTime) values(?,?)",
      {
        replacements: [tagName, time],
        type: QueryTypes.INSERT,
      }
    );
    return res;
  }

  async queryInfoService(id) {
    const res = await seq.query("select * from `bl-tag` where id = ?", {
      replacements: [id],
      type: QueryTypes.SELECT,
    });
    if (res && res[0]) {
      return res[0];
    }
    console.log(res);
  }

  async deleteService({ id }) {
    const res = await seq.query("delete from `bl-tag` where id = ?", {
      replacements: [id],
      type: QueryTypes.DELETE,
    });
  }

  async deleteSelectService(ids) {
    // 动态生成id，直接传数组
    const res = seq.query("delete from `bl-tag` where id in (?)", {
      replacements: [ids],
      type: QueryTypes.DELETE,
    });
  }
  async queryInfoServiceList(ids) {
    const arr = ids.split(",");
    const res = await seq.query("select * from `bl-tag` where id in (?)", {
      replacements: [arr],
      type: QueryTypes.SELECT,
    });
    if (res && res.length > 0) {
      return res;
    }
    console.log(res);
  }
}

module.exports = new TagService();
